<template>
	<view>
		<view class="search-box">
			<uni-search-bar :radius='100' @input="input" cancelButton="none"></uni-search-bar>
		</view>
		<view class="sugg-list" v-show="show">
			<view class="sugg-item" v-for="(item,index) in searchResults" :key="index" @click="gotoDetail(item)">
				<view class="goods-name">{{item.goods_name}}</view>
				<uni-icons type="arrowright" size="16"></uni-icons>
			</view>
		</view>
		<view class="history-box" v-show="!show">
			<view class="history-title">
				<view>搜索历史</view>
				<uni-icons type="trash-filled" size="16" @click="cleanHistory"></uni-icons>
			</view>
			<view class="history-list">
				<uni-tag v-for="(item,index) in historyList" :key="index" :text="item" @click="gotoGoodsList(item)"></uni-tag>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				timer:null,
				kw:'',
				searchResults:[],
				historyList: JSON.parse(uni.getStorageSync('kw')||'[]'),
			};
		},
		computed:{
			show:function(){
				return this.searchResults.length === 0 ? false : true
			}
		},
		methods:{
			input(e){
				clearTimeout(this.timer)
				this.timer = setTimeout(()=>{
					this.kw = e.value
					this.getSearchList()
					console.log(e.value)
				},500)
				
			},
			async getSearchList(){
				//判断关键词是否为空
				if(this.kw.length === 0){
					this.searchResults = []
					return
				}
				 const {data:res} = await uni.$http.get('/api/public/v1/goods/qsearch',{query:this.kw})
				 //保存搜索关键字
				 this.saveSearchHistory()
				 if(res.meta.status !== 200){
					 return uni.$showMsg()
				 }
				 this.searchResults = res.message
			},
			//保存关键词到数组
			saveSearchHistory(){
				this.historyList = [...new Set([this.kw,...this.historyList])]
				uni.setStorageSync('kw',JSON.stringify(this.historyList))
			},
			cleanHistory(){
				  // 清空 data 中保存的搜索历史
				  this.historyList = []
				  // 清空本地存储中记录的搜索历史
				  uni.setStorageSync('kw', '[]')
			},
			gotoGoodsList(kw){
				uni.navigateTo({
					url: '/subpkg/goods_list/goods_list?query='+kw,
				});
			},
			gotoDetail(item){
				uni.navigateTo({
					url: '/subpkg/goods_detail/goods_detail?goodId='+item.goods_id,
				});
			}
		}
	}
</script>

<style lang="scss">
.search-box{
	position: sticky;
	top:0;
	z-index:99;
}
.sugg-list{
	padding: 0 5px;
	.sugg-item{
		font-size: 12px;
		padding: 13px 0;
		border-bottom: 1px solid #efefef;
		display: flex;
		justify-content: space-between;
		.goods-name{
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			margin-right: 3px;
		}
	}
}
.history-box {
	padding: 0 5px;
	.history-title{
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 40px;
		font-size: 13px;
		border-bottom: 1px solid #efefef;
	}
	.history-list{
		display: flex;
		flex-wrap: wrap;
		.uni-tag{
			margin-top: 5px;
			margin-right: 5px;
		}
	}
}
</style>
